package service;

import java.util.HashMap;
import java.util.Map;

import util.EmailUtil;
import util.EmailVerifyCodeUtil;
import util.MD5Util;
import util.SHA1Util;
import dao.UserDao;
import entity.User;

public class UserService {
	public void saveUser(User user) throws Exception{
		String passwordmd5 = MD5Util.getMD5String(user.getPassword());
		String passwordsha1 = SHA1Util.getSHA1String(user.getPassword());
		String email_verify_code = EmailVerifyCodeUtil.getNumber();
		int user_integral = 0;
		int is_email_verify = 0;
		user.setPasswordmd5(passwordmd5);
		user.setPasswordsha1(passwordsha1);
		user.setEmail_verify_code(email_verify_code);
		user.setUser_integral(user_integral);
		user.setIs_email_verify(is_email_verify);
		new UserDao().saveUser(user);
		
		Map<String, String> param = new HashMap<String, String>();
		param.put("to", user.getEmail());
		param.put("email_verify_code", email_verify_code);
		EmailUtil.sendSimpleEmail(param);
	}
	
	public User validateEmailVC(String email, String validatecode) throws Exception{
		UserDao dao = new UserDao();
		User user = dao.queryUserByEmail(email);
		if (user.getEmail_verify_code().equals(validatecode)) {
			user.setIs_email_verify(new Integer(1));
			dao.updateUser(user);
			return user;
		}
		return user;
	}
	
	public User queryUserByEmail(String email) throws Exception {
		return new UserDao().queryUserByEmail(email);
	}
	
	public void updateUser(User user) throws Exception {
		new UserDao().updateUser(user);
	}
}
